package com.example.zluserservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.zluserservice.client.RoleFeignClient;
import com.example.zluserservice.common.annotation.DataScope;
import com.example.zluserservice.common.base.PageResponse;
import com.example.zluserservice.common.base.ResponseResult;
import com.example.zluserservice.common.util.UserThreadLocal;
import com.example.zluserservice.dto.request.LoginReqDTO;
import com.example.zluserservice.dto.request.RegisterReqDTO;
import com.example.zluserservice.dto.request.ResetPasswordReqDTO;
import com.example.zluserservice.dto.request.UserReqDTO;
import com.example.zluserservice.dto.response.RegisterResDTO;
import com.example.zluserservice.dto.response.UserResDTO;
import com.example.zluserservice.entity.User;
import com.example.zluserservice.service.IUserService;
import com.example.zluserservice.service.LoginService;
import com.example.zluserservice.service.RegisterService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.management.relation.Role;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author zhenliu（孙凌岳）
 * @Description 用户服务 - 系统用户控制器
 * @Date 2025/6/14 12:10
 * @Version 1.0
 */
@Slf4j
@Api(tags = "用户服务 - 系统用户控制器")
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @Resource
    private LoginService loginService;

    @Resource
    private RoleFeignClient roleFeignClient;

    @Resource
    private RegisterService registerService;

    /**
     *  保存用户
     * @param userReqDTO 用户dto对象
     * @return UserResDTO
     */
    @PutMapping
    @ApiOperation(value = "添加用户", notes = "新增系统用户信息")
    @ApiImplicitParam(name = "userDto",value = "用户DTO对象",required = true,dataType = "UserDto")
    @ApiOperationSupport(includeParameters = {"userDto.email","userDto.dataState","userDto.deptNo","userDto.deptPostUserVoSet","userDto.mobile","userDto.postNo","userDto.realName","userDto.roleVoIds"})
    public ResponseResult<UserResDTO> createUser(@RequestBody UserReqDTO userReqDTO) {
        UserResDTO userVoResult = userService.createUser(userReqDTO);
        return ResponseResult.success(userVoResult);
    }

    /**
     * 修改用户
     * @param userReqDTO 用户DTO对象
     * @return Boolean 是否修改成功
     */
    @PatchMapping
    @ApiOperation(value = "修改用户", notes = "根据用户ID修改信息")
    @ApiImplicitParam(name = "userDto",value = "用户DTO对象",required = true,dataType = "UserDto")
    @ApiOperationSupport(includeParameters = {"userDto.email","userDto.dataState","userDto.deptNo","userDto.deptPostUserVoSet","userDto.mobile","userDto.postNo","userDto.realName","userDto.roleVoIds"})
    public ResponseResult<Boolean> updateUser(@RequestBody UserReqDTO userReqDTO) {
        Boolean flag = userService.updateUser(userReqDTO);
        return ResponseResult.success(flag);
    }

    /**
     * 根据id删除用户
     * @param userId
     * @return
     */
    @DeleteMapping("/remove/{userId}")
    @ApiOperation(value = "删除用户", notes = "根据用户ID删除用户信息")
    public ResponseResult remove(@PathVariable Long userId) {
        return ResponseResult.success(userService.deleteUserById(userId));
    }

    /**
     * 重置密码
     * @param resetPasswordReqDTO
     * @return
     */
    @PostMapping("reset-passwords")
    @ApiOperation(value = "重置密码", notes = "根据用户ID重置用户密码")
    @ApiImplicitParam(paramType = "path",name = "userId",value = "用戶Id",required = true,dataType = "String")
    public ResponseResult<Boolean> resetPasswords(@RequestBody ResetPasswordReqDTO resetPasswordReqDTO) {
        Boolean flag = userService.resetPasswords(resetPasswordReqDTO.getUserId());
        return ResponseResult.success(flag);
    }

    /***
     *  多条件查询用户分页列表
     * @param userReqDTO 用户DTO查询条件
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @return: Page<UserVo>
     */
    @PostMapping("page/{pageNum}/{pageSize}")
    @ApiOperation(value = "用户分页查询", notes = "根据条件分页查询用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userDto",value = "用户DTO对象",required = true,dataType = "UserDto"),
            @ApiImplicitParam(paramType = "path",name = "pageNum",value = "页码",example = "1",dataType = "Integer"),
            @ApiImplicitParam(paramType = "path",name = "pageSize",value = "每页条数",example = "10",dataType = "Integer")
    })
    @ApiOperationSupport(includeParameters = {"userDto.username","userDto.email","userDto.dataState","userDto.deptNo"})
    @DataScope
    public ResponseResult<PageResponse<UserResDTO>> findUserResDTOPage(
            @RequestBody UserReqDTO userReqDTO,
            @PathVariable("pageNum") int pageNum,
            @PathVariable("pageSize") int pageSize) {
        PageResponse<UserResDTO> userResDTOPageResponse = userService.findUserPage(userReqDTO, pageNum, pageSize);
        return ResponseResult.success(userResDTOPageResponse);
    }

    /**
     * 登录接口
     * @param loginReqDto
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "根据用户名密码登录")
    public ResponseResult<UserResDTO> login(@RequestBody LoginReqDTO loginReqDto, HttpServletRequest request){
        UserResDTO userResDTO = loginService.login(loginReqDto,request);
        return ResponseResult.success(userResDTO);
    }

    /**
     * 注册接口
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册", notes = "用户注册功能")
    public ResponseResult<RegisterResDTO> register(@RequestBody RegisterReqDTO registerReqDTO){
        RegisterResDTO registered = registerService.register(registerReqDTO);
        return ResponseResult.success(registered);
    }

    @GetMapping("current-user")
    @ApiOperation(value = "获取当前用户信息", notes = "解析JWT获取当前登录用户信息")
    ResponseResult<UserResDTO> findCurrentUser()  {
        String subject = UserThreadLocal.getSubject();
        UserResDTO userVo = JSONObject.parseObject(subject,UserResDTO.class);
        return ResponseResult.success(userVo);
    }


    @PostMapping("/testAdd")
    @ApiOperation(value = "测试添加用户（开发用）", notes = "测试分库分表添加用户")
    public boolean addUser(@RequestBody User user) {
        userService.testAdd(user);
        return true;
    }

    @GetMapping("/feign")
    @ApiOperation(value = "测试 Feign 接口调用", notes = "测试用户服务调用角色服务")
    public String  testFeign() {
       return roleFeignClient.testPermission();
    }
}